package data

import (
	"context"
	"encoding/json"

	"github.com/streadway/amqp"
)

// StockRollbackMsg 回滚库存消息结构体
type StockRollbackMsg struct {
	SeckillProductID int64 `json:"seckill_product_id"`
	Quantity         int   `json:"quantity"`
}

// MQClient 封装RabbitMQ连接
type MQClient struct {
	conn    *amqp.Connection
	Channel *amqp.Channel // 导出字段，便于外部访问
}

func NewMQClient(amqpURL string) (*MQClient, error) {
	conn, err := amqp.Dial(amqpURL)
	if err != nil {
		return nil, err
	}
	ch, err := conn.Channel()
	if err != nil {
		return nil, err
	}
	return &MQClient{conn: conn, Channel: ch}, nil
}

func (mq *MQClient) Close() {
	if mq.Channel != nil {
		mq.Channel.Close()
	}
	if mq.conn != nil {
		mq.conn.Close()
	}
}

// PublishRollback 发布回滚库存消息
func (mq *MQClient) PublishRollback(ctx context.Context, msg StockRollbackMsg) error {
	body, _ := json.Marshal(msg)
	return mq.Channel.Publish(
		"",                 // 默认交换机
		"seckill_rollback", // 队列名
		false, false,
		amqp.Publishing{
			ContentType: "application/json",
			Body:        body,
		},
	)
}
